<template>
  <div id="operate-freightModule">
    <el-container style="overflow-x:hidden;overflow-y:hidden; height:100%;">
      <el-scrollbar
        style="width:100%;height:100%;white-space: nowrap;"
        @mousewheel.native="wheel"
        ref="roleRoll"
        class="roleRoll"
      >
        <el-header>
          <el-button type="primary" icon="el-icon-edit" 
          @click="handleEdit(1)"
          v-permission="'operation:freight:create'"
            >添加</el-button
          >
        </el-header>

        <el-main>
          <el-table
            :data="tableData"
            style="width: 100%;"
            :default-sort="{ prop: 'date', order: 'descending' }"
            align="center border show-summary"
            border
          >
            <!-- 列表数据 -->
            <el-table-column
              prop="freightTemplateDO.id"
              label="模板编号"
            ></el-table-column>
            <el-table-column
              prop="freightTemplateDO.templateName"
              label="模板名称"
              width="300"
            ></el-table-column>
            <el-table-column
              prop="freightTemplateDO.spuLocation"
              label="宝贝地址"
            >
            </el-table-column>
            <el-table-column label="发货期限">
              <template slot-scope="scope">
                {{
                  scope.row.freightTemplateDO.deliveryDeadline
                    | deliveryDeadline
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="freightTemplateDO.defaultFreePrice"
              label="默认包邮门栏"
            >
              <template slot-scope="scope">
                {{ scope.row.freightTemplateDO.defaultFreePrice | postage }}
              </template>
            </el-table-column>
            <el-table-column label="默认计费首次发货数量">
              <template slot-scope="scope">
                {{ scope.row.freightTemplateDO.defaultFirstNum | quantity }}
              </template>
            </el-table-column>
            <el-table-column
              prop="freightTemplateDO.defaultFirstMoney"
              label="默认计费首次发货价格"
            >
              <template slot-scope="scope">
                {{ scope.row.freightTemplateDO.defaultFirstMoney | money }}
              </template>
            </el-table-column>
            <el-table-column
              prop="freightTemplateDO.defaultContinueNum"
              label="默认计费续费数量"
            >
              <template slot-scope="scope">
                {{ scope.row.freightTemplateDO.defaultContinueNum | quantity }}
              </template>
            </el-table-column>
            <el-table-column
              prop="freightTemplateDO.defaultContinueMoney"
              label="默认计费续费价格"
            >
              <template slot-scope="scope">
                {{ scope.row.freightTemplateDO.defaultContinueMoney | money }}
              </template>
            </el-table-column>
            <el-table-column
              prop="freightTemplateCarriageDOList.length"
              label="指定地区数量"
            >
            </el-table-column>
            <el-table-column label="操作" width="300">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(2, scope.$index, scope.row)"
                  v-permission="'operation:freight:update'"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  v-permission="'operation:freight:delete'"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-scrollbar>
      <!-- 滚动组件结束 -->
    </el-container>
    <!-- 主要内容结束 -->

    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      center
      class="freight-dialog"
    >
      <!-- 对话框表单 -->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
        style="width:700px;margin:auto"
        label-position="left"
      >
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="ruleForm.templateName"></el-input>
        </el-form-item>
        <el-form-item label="发货地址" prop="spuLocation">
          <el-input v-model="ruleForm.spuLocation"></el-input>
        </el-form-item>
        <el-form-item label="发货期限" prop="deliveryDeadline">
          <el-input v-model="ruleForm.deliveryDeadline">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="是否包邮">
          <el-radio-group v-model="radio">
            <el-radio :label="1">坚决不包邮</el-radio>
            <el-radio :label="2">卖家承担包邮</el-radio>
            <el-radio :label="3">设定满额包邮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="默认包邮额度"
          prop="defaultFreePrice"
          v-if="radio == 3"
        >
          <el-input
            v-model="ruleForm.defaultFreePrice"
            placeholder="默认包邮额度"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="计费首次数量" prop="defaultFirstNum" v-show="radio != 2">
          <el-input v-model="ruleForm.defaultFirstNum">
            <template slot="append"
              >件
              <el-tooltip
                class="item"
                effect="dark"
                content="当用户购买商品数量小于 ‘这个数’ 就支付默认首次发货价格的运费"
                placement="top-start"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="计费首次价格" prop="defaultFirstPrice" v-show="radio != 2">
          <el-input v-model="ruleForm.defaultFirstPrice">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="计费续件数量" prop="defaultContinueNum" v-show="radio != 2">
          <el-input v-model="ruleForm.defaultContinueNum">
            <template slot="append"
              >件
              <el-tooltip
                class="item"
                effect="dark"
                content="当用户购买数量高于 ‘首次发货数量’ 每多 N 件，就须额外支付 ‘续件价格’"
                placement="top-start"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="计费续件价格" prop="defaultContinuePrice" v-show="radio != 2">
          <el-input v-model="ruleForm.defaultContinuePrice">
            <template slot="append"
              >元
              <el-tooltip
                class="item"
                effect="dark"
                content="若不需要计件额外算运费，则直接填0即可"
                placement="top-start"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="指定地区价格">
          <el-button type="primary" plain @click="nestAdd">添加</el-button>
        </el-form-item>
        <el-form-item
          prop="freightTemplateCarriageDOList"
          style="width: 120%;"
          class="nesttable"
        >
          <el-table
            :data="ruleForm.freightTemplateCarriageDOList"
            style="width: 100%;"
          >
            <el-table-column
              prop="id"
              label="指定地区ID"
              v-if="title != '创造'"
            >
            </el-table-column>
            <el-table-column prop="designatedArea" label="指定省份">
            </el-table-column>
            <el-table-column prop="firstNum" label="首次数量">
            </el-table-column>
            <el-table-column prop="firstMoney" label="首次价格">
            </el-table-column>
            <el-table-column prop="continueNum" label="续件数量">
            </el-table-column>
            <el-table-column prop="continueMoney" label="续件价格">
            </el-table-column>
            <el-table-column prop="freePrice" label="满额包邮门栏">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="nestHandleDelete(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确定</el-button
        >
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 对话框表单结束 -->
    <!-- 对话框表单嵌套表单开始 -->
    <el-dialog
      title="添加指定地址"
      :visible.sync="nestDialogFormVisible"
      class="nest-dialog"
    >
      <el-form
        :model="nestRuleForm"
        status-icon
        :rules="nestRules"
        ref="nestRuleForm"
        label-width="120px"
        class="demo-nestRuleForm"
        style="width:400px;margin-left: 50px;"
        label-position="left"
      >
        <el-form-item label="包邮门栏" prop="freePrice">
          <el-input v-model="nestRuleForm.freePrice">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="首次数量" prop="firstNum">
          <el-input v-model="nestRuleForm.firstNum">
            <template slot="append">件</template>
          </el-input>
        </el-form-item>
        <el-form-item label="首次价格" prop="firstMoney">
          <el-input v-model="nestRuleForm.firstMoney">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="续件数量" prop="continueNum">
          <el-input v-model="nestRuleForm.continueNum">
            <template slot="append">件</template>
          </el-input>
        </el-form-item>
        <el-form-item label="续件价格" prop="continueMoney">
          <el-input v-model="nestRuleForm.continueMoney">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="指定地区" prop="designatedArea" style="width:150%">
          <el-checkbox-group v-model="nestRuleForm.designatedArea">
            <el-checkbox v-for="city in cities" :label="city" :key="city">{{
              city
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="nestDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="nestSubmitForm('nestRuleForm')"
          >确定</el-button
        >
      </span>
    </el-dialog>
    <!-- 对话框表单嵌套表单结束 -->
  </div>
</template>

<script>
import freight from "@/api/freight";
export default {
  data() {
    var validateName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("模板名称不能为空"));
      } else {
        callback();
      }
    };
    var validateDeadline = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("发货期限不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
          if (value < 10000000) {
            callback();
          } else {
            callback(new Error("需要小于1千万"));
          }
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validateFreePrice = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("包邮门栏额度不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
          if (value < 10000000) {
            callback();
          } else {
            callback(new Error("需要小于1千万"));
          }
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validateFirstPrice = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("首次计费价格不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
          if (value < 10000000) {
            callback();
          } else {
            callback(new Error("需要小于1千万"));
          }
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validateFirstNum = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("首次计费数量不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
          if (value < 10000000) {
            callback();
          } else {
            callback(new Error("需要小于1千万"));
          }
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validateContinuePrice = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("续件计费价格不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
          if (value < 10000000) {
            callback();
          } else {
            callback(new Error("需要小于1千万"));
          }
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validateContinueNum = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("续件计费数量不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
          if (value < 10000000) {
            callback();
          } else {
            callback(new Error("需要小于1千万"));
          }
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validateCities = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error("至少选择一个地区"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        //表单数据
        templateName: "", //模板名称
        deliveryDeadline: "", //发货期限
        defaultFreePrice: "", //默认满价包邮系列
        defaultFirstNum: "", //默认首件数量
        defaultFirstPrice: "", //默认首费
        defaultContinueNum: "", //默认续件数量
        defaultContinuePrice: "", //默认续费
        spuLocation: "", //宝贝地址
        freightTemplateCarriageDOList: [], //特殊运费区
      },
      radio: 3, //单选框
      roledata: "", //选中的数据
      index: "", //选中的下标
      rules: {
        //表单验证
        templateName: [
          { required: true, validator: validateName, trigger: "blur" },
        ],
        deliveryDeadline: [
          { required: true, validator: validateDeadline, trigger: "blur" },
        ],
        defaultFreePrice: [
          { required: true, validator: validateFreePrice, trigger: "blur" },
        ],
        defaultFirstPrice: [
          { required: true, validator: validateFirstPrice, trigger: "blur" },
        ],
        defaultFirstNum: [
          { required: true, validator: validateFirstNum, trigger: "blur" },
        ],
        defaultContinuePrice: [
          { required: true, validator: validateContinuePrice, trigger: "blur" },
        ],
        defaultContinueNum: [
          { required: true, validator: validateContinueNum, trigger: "blur" },
        ],
      },
      title: "创造", //对话框的名字
      dialogFormVisible: false, //对话框表单的隐藏显示
      nestDialogFormVisible: false, //嵌套对话框表单的隐藏显示
      tableData: [], //后台全部管理员列表数据
      nestRuleForm: {
        //表单数据
        freePrice: "", //满价包邮系列
        firstNum: "", //首件数量
        firstMoney: "", //首费
        continueNum: "", //续费
        continueMoney: "", //续件数量
        designatedArea: [], //指定地区
      },
      nestRules: {
        //嵌套表单验证
        freePrice: [
          { required: true, validator: validateFreePrice, trigger: "blur" },
        ],
        firstMoney: [
          { required: true, validator: validateFirstPrice, trigger: "blur" },
        ],
        firstNum: [
          { required: true, validator: validateFirstNum, trigger: "blur" },
        ],
        continueMoney: [
          { required: true, validator: validateContinuePrice, trigger: "blur" },
        ],
        continueNum: [
          { required: true, validator: validateContinueNum, trigger: "blur" },
        ],
        designatedArea: [
          { required: true, validator: validateCities, trigger: "blur" },
        ],
      },
      cities: [
        //城市
        "北京市",
        "天津市",
        "河北省",
        "山西省",
        "内蒙古自治区",
        "辽宁省",
        "吉林省",
        "黑龙江省",
        "上海市",
        "江苏省",
        "浙江省",
        "安徽省",
        "福建省",
        "江西省",
        "山东省",
        "河南省",
        "湖北省",
        "湖南省",
        "广东省",
        "广西壮族自治区",
        "海南省",
        "重庆市",
        "四川省",
        "贵州省",
        "云南省",
        "西藏自治区",
        "陕西省",
        "甘肃省",
        "青海省",
        "宁夏回族自治区",
        "新疆维吾尔自治区",
        "台湾省",
        "香港特别行政区",
        "澳门特别行政区",
      ],
    };
  },

  created: function() {
    //一开始的渲染数据
    this.onSubmit();
  },
  filters: {
    deliveryDeadline(value) {
      return value + "天";
    },
    postage(value) {
      if (value > 0) {
        return "满" + value / 100 + "元包邮";
      } else if (value == 0) {
        return "包邮";
      } else {
        return "不包邮";
      }
    },
    quantity(value) {
      return value + "件";
    },
    money(value) {
      return value / 100 + "元";
    },
  },
  methods: {
    onSubmit() {
      //查询
      let that = this;
      freight
        .freightInquire()
        //查询接口封装
        .then((res) => {
          console.log(res);
          that.tableData = res.data.data; //获取数据赋值
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    handleEdit(digit, index, row) {
      //编辑和添加
      let that = this;
      this.dialogFormVisible = true;
      this.resetForm("ruleForm");
      if (digit == 1) {
        this.title = "创造";
        setTimeout(function() {
          that.radio = 3;
          that.ruleForm.defaultFreePrice = 68;
          that.ruleForm.defaultFirstNum= 1, //默认首件数量
          that.ruleForm.defaultFirstPrice= 1, //默认首费
          that.ruleForm.defaultContinueNum= 1, //默认续件数量
          that.ruleForm.defaultContinuePrice = 1, //默认续费
          that.ruleForm.freightTemplateCarriageDOList = [];
        }, 50);
      } else {
        //防止重置时没有数据
        setTimeout(function() {
          console.log(row);
          if (row.freightTemplateDO.defaultFreePrice > 0) {
            //根据包邮门栏的值确定单选按钮的选择
            that.radio = 3;
          } else if (row.freightTemplateDO.defaultFreePrice == 0) {
            that.radio = 2;
          } else {
            that.radio = 1;
          }
          that.title = "编辑";
          that.roledata = row;
          that.index = index;
          for (const i in that.ruleForm) {
            that.ruleForm[i] = row.freightTemplateDO[i];
          }
          that.ruleForm.defaultFirstPrice =row.freightTemplateDO.defaultFirstMoney / 100;
          that.ruleForm.defaultContinuePrice =row.freightTemplateDO.defaultContinueMoney / 100;
          that.ruleForm.defaultFreePrice =row.freightTemplateDO.defaultFreePrice / 100;
          that.ruleForm.freightTemplateCarriageDOList =row.freightTemplateCarriageDOList;
        }, 50);
      }
    },
    nestAdd() {
      //嵌套点击添加重置
      this.nestDialogFormVisible = true;
      this.resetForm("nestRuleForm");
    },
    nestSubmitForm(formName) {
      //嵌套提交
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.nestDialogFormVisible = false;
          let data = JSON.parse(JSON.stringify(that.nestRuleForm)); //深度克隆
          let string = "";
          for (let i = 0; i < data.designatedArea.length; i++) {
            //数组拼接逗号
            string = string + data.designatedArea[i] + ",";
          }
          data.designatedArea = string.substr(0, string.length - 1);
          that.ruleForm.freightTemplateCarriageDOList.push(data);
        } else {
          return false;
        }
      });
    },
    nestHandleDelete(index) {
      //嵌套删除
      this.ruleForm.freightTemplateCarriageDOList.splice(index, 1);
    },
    submitForm(formName) {
      //提交
      if (this.radio == 1) {
        //默认包邮额度的隐藏显示判断
        this.ruleForm.defaultFreePrice = -100;
      } else if (this.radio == 2) {
        this.ruleForm.defaultFreePrice = 0;
      }
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.defaultFreePrice != 0) {
            this.ruleForm.defaultFreePrice = this.ruleForm.defaultFreePrice * 100;
            this.ruleForm.defaultFirstPrice = this.ruleForm.defaultFirstPrice * 100;
            this.ruleForm.defaultContinuePrice =this.ruleForm.defaultContinuePrice * 100;
          }
          that.ruleForm.freightTemplateCarriageDOList = JSON.stringify(
            that.ruleForm.freightTemplateCarriageDOList
          );
          this.dialogFormVisible = false;
          if (that.title == "创造") {
            //添加
            that.addition();
          } else {
            //编辑
            that.compile();
          }
        } else {
          return false;
        }
      });
    },
    addition() {
      //添加
      let that = this;
      freight
        .addFreightTemplate(that.ruleForm)
        //添加封装接口
        .then(function(res) {
          if (res.data.errmsg == "成功") {
            that.topTips(res.data.errmsg, "success");
            that.onSubmit();
          } else {
            that.topTips(res.data.errmsg, "warning");
          }
        });
    },
    compile() {
      //编制
      let that = this;
      let data = Object.assign(that.ruleForm, {
        templateId: that.roledata.freightTemplateDO.id,
      });
      freight
        .updateFreightTemplate(data)
        //编制封装接口
        .then(function(res) {
          if (res.data.errmsg == "成功") {
            that.topTips(res.data.errmsg, "success");
            that.onSubmit();
          } else {
            that.topTips(res.data.errmsg, "warning");
          }
        });
    },
    resetForm(formName) {
      //重置验证
      let that = this;
      setTimeout(function() {
        that.$refs[formName].resetFields();
      }, 50);
    },
    handleDelete(index, row) {
      //删除
      console.log(index, row);
      let that = this;
      this.$confirm(
        "此操作将永久删除--" +
          row.freightTemplateDO.templateName +
          "--, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          freight
            .deleteFreightTemplate({
              //删除封装接口
              templateId: row.freightTemplateDO.id,
            })
            .then(function(res) {
              if (res.data.errmsg == "成功") {
                that.topTips(res.data.errmsg, "success");
                that.tableData.splice(index, 1);
              } else {
                that.topTips(res.data.errmsg, "error");
              }
            });
        })
        .catch(() => {
          this.topTips("已取消删除", "info");
        });
    },
    wheel(e) {
      //滚动事件
      e = e || window.event;
      if (e.wheelDelta) {
        if (e.wheelDelta < 0) {
          //控制滚动的方向
          //向下
          this.$refs.roleRoll.wrap.scrollTop += 20;
        } else {
          this.$refs.roleRoll.wrap.scrollTop -= 20;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
#operate-freightModule {
  //内容填满
  height: 100%;
}
.el-main {
  line-height: 0px !important;
}
.concer-input {
  //查询文本框
  width: 25%;
  margin-right: 10px;
}
.el-header {
  //查询布局
  line-height: 52px;
  height: auto !important;
}
.demo-form-inline {
  //查询布局
  white-space: pre-line;
}
.demo-form-inline > div {
  //查询布局
  margin-bottom: 0px;
}
</style>

<style>
.el-dialog__header,
.dialog-footer,
.el-tree-node__label,
.el-dialog__footer,
.el-checkbox,
.custom-tree-node {
  /*对话框的行高*/
  line-height: 0px;
}
.cell {
  /*列表居中*/
  text-align: center;
}
.freight-dialog {
  overflow-x: hidden;
}
.freight-dialog .el-dialog {
  /*对话框样式*/
  width: 100%;
  height: auto;
  margin: auto !important;
}
.nest-dialog .el-dialog {
  /*嵌套对话框样式*/
  width: 75%;
}
.nesttable .el-form-item__content {
  margin-left: 0px !important;
}
::-webkit-scrollbar {
  /*对话框的隐藏滚动条但是可以滚动，滚动条的宽度*/
  width: 0px !important;
}
</style>
